$.fn.extend({
	// 操作锁
	isLocked: function() {
		return this.data('locked');
	},
	lock: function() {
		if (this.isLocked()) {
			return false;
		}
		this.data("locked", true);
		return true;
	},
	unlock: function(rightNow) {
		var $this = this;
		if (!rightNow) {
			setTimeout(function() {
				$this.removeData("locked");
			},1000);
		} else {
			$this.removeData("locked");
		}
		return $this;
	},
	// 加载状态
	isLoading: function() {
		return this.data("loading");
	},
	loading: function() {
		return this.data("loading", true); 
	},
	loaded: function() {
		return this.data("loading", false); 
	},
	// 操作提示
	defMsg: function(msg, type) {
		var $this = this;
		// 如果执行的是加载,则延迟0.5秒显示, 如果0.5秒后还没有加载完再显示
		if (type === 'load') {
			clearTimeout($this.data("msg_timeout_index"))
			var index = setTimeout(function() {
				if ($this.isLoading()) {
					if (hasMsg_()) {
						resetMsg_();
					} else {
						setMsg_();
					}						
				}
			}, 500);				
			$this.data("msg_timeout_index", index);
			
		} else {
			if (hasMsg_()) {
				resetMsg_();
			} else {
				setMsg_();
			}
		}
		
		function hasMsg_() {
			return $this.data('hasMsg');
		}
		
		function resetMsg_() {
			$this.trigger('changeMsg', [msg, type]);
		}
		
		function setMsg_() {
			var $el = $('.tipbox');
			if ($el.length === 0) {
				$el = $("<div class='tipbox' style='z-index: 99999;position: fixed;width: 100%;text-align: center;'></div>");
				$("body").prepend($el);
			}
			var $tip = $('<div class="alert" role="alert"><div style="display: inline-block;"></div></div>');
			$el.append($tip);
			$this.data('hasMsg', true);
			
			$this.on('changeMsg', function(event, msg, type) {
				$tip.removeClass("alert-success,alert-danger,alert-load");
				$tip.addClass(type);
				$tip.children("div:eq(0)").html(msg);
				if (type !== 'alert-load') {
					$tip.stop(true,true).show().delay(3000).fadeOut(function() {$tip.hide();});
				} else {
					$tip.addClass("alert-success");
					$tip.show();
				}
				return false;
			});
			$this.on('hideMsg', function() {
				$tip.fadeOut();
				return false;
			});
			
			$this.trigger('changeMsg', [msg, type]);
		} 
		
		return $this;
	},
	hideMsg: function() {
		return this.loaded().unlock(true).trigger('hideMsg');
	},
	infoMsg: function(msg) {
		return this.loaded().unlock().defMsg(msg, "alert-success");
	},
	loadMsg: function(msg) {
		return this.loading().defMsg(msg, 'alert-load');
	},
	failMsg: function(msg) {
		return this.loaded().unlock().defMsg(msg, 'alert-danger');
	}
});